import torch

# 1.加法支持广播
x = torch.empty(5, 1, 4, 1)
y = torch.empty(   3, 1, 1)
print((x + y).size())  # torch.Size([5, 3, 4, 1])

x = torch.empty(      1)
y = torch.empty(3, 1, 7)
print((x + y).size())  # torch.Size([3, 1, 7])

# 2和3不满足其中一个为1空，不能广播
x = torch.empty(5, 2, 4, 1)
y = torch.empty(   3, 1, 1)
# print((x + y).size())  # 报错 RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1

# 原地写操作不能因广播而改变自身形状
x = torch.empty(5, 3, 4, 1)
y = torch.empty(   3, 1, 1)
print(x.add_(y).size())  # torch.Size([5, 3, 4, 1])  x为原地写，但是x的形状没变，因此可以相加

x = torch.empty(5, 1, 4, 1)
y = torch.empty(   3, 1, 1)
# x原地写，由于广播改变自身shape了，因此报错
print(x.add_(y).size())  # RuntimeError: output with shape [5, 1, 4, 1] doesn't match the broadcast shape [5, 3, 4, 1]


